package com.vitetest.api.service;

import com.vitetest.api.dto.ProductRequest;
import com.vitetest.api.dto.ProductResponse;
import com.vitetest.api.entity.Product;
import com.vitetest.api.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    /**
     * 添加新商品
     */
    public ProductResponse addProduct(ProductRequest request) {
        // 检查商品名称是否已存在
        Optional<Product> existingProduct = productRepository.findByName(request.getName());
        if (existingProduct.isPresent()) {
            throw new RuntimeException("商品名称已存在：" + request.getName());
        }
        
        // 创建新商品
        Product product = new Product();
        product.setName(request.getName());
        product.setDescription(request.getDescription());
        product.setPrice(request.getPrice());
        product.setStock(request.getStock());
        product.setCategory(request.getCategory());
        product.setImageUrl(request.getImageUrl());
        product.setIsActive(true);
        
        Product savedProduct = productRepository.save(product);
        return convertToResponse(savedProduct);
    }
    
    /**
     * 根据ID获取商品
     */
    public ProductResponse getProductById(Long id) {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在，ID：" + id));
        return convertToResponse(product);
    }
    
    /**
     * 获取所有激活的商品
     */
    public List<ProductResponse> getAllActiveProducts() {
        List<Product> products = productRepository.findByIsActiveTrue();
        return products.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 分页获取激活的商品
     */
    public Page<ProductResponse> getActiveProductsPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Product> products = productRepository.findByIsActiveTrue(pageable);
        return products.map(this::convertToResponse);
    }
    
    /**
     * 根据分类获取商品
     */
    public List<ProductResponse> getProductsByCategory(String category) {
        List<Product> products = productRepository.findByCategoryAndIsActiveTrue(category);
        return products.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据名称搜索商品
     */
    public List<ProductResponse> searchProductsByName(String name) {
        List<Product> products = productRepository.findByNameContainingAndIsActiveTrue(name);
        return products.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据价格范围搜索商品
     */
    public List<ProductResponse> searchProductsByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) {
        List<Product> products = productRepository.findByPriceBetweenAndIsActiveTrue(minPrice, maxPrice);
        return products.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 更新商品信息
     */
    public ProductResponse updateProduct(Long id, ProductRequest request) {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在，ID：" + id));
        
        // 检查名称是否与其他商品重复
        Optional<Product> existingProduct = productRepository.findByName(request.getName());
        if (existingProduct.isPresent() && !existingProduct.get().getId().equals(id)) {
            throw new RuntimeException("商品名称已存在：" + request.getName());
        }
        
        product.setName(request.getName());
        product.setDescription(request.getDescription());
        product.setPrice(request.getPrice());
        product.setStock(request.getStock());
        product.setCategory(request.getCategory());
        if (request.getImageUrl() != null) {
            product.setImageUrl(request.getImageUrl());
        }
        
        Product updatedProduct = productRepository.save(product);
        return convertToResponse(updatedProduct);
    }
    
    /**
     * 删除商品（软删除）
     */
    public void deleteProduct(Long id) {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在，ID：" + id));
        
        product.setIsActive(false);
        productRepository.save(product);
    }
    
    /**
     * 更新商品库存
     */
    public ProductResponse updateProductStock(Long id, Integer newStock) {
        if (newStock < 0) {
            throw new RuntimeException("库存不能为负数");
        }
        
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在，ID：" + id));
        
        product.setStock(newStock);
        Product updatedProduct = productRepository.save(product);
        return convertToResponse(updatedProduct);
    }
    
    /**
     * 获取库存不足的商品
     */
    public List<ProductResponse> getLowStockProducts(Integer threshold) {
        List<Product> products = productRepository.findByStockLessThanAndIsActiveTrue(threshold);
        return products.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取所有商品分类
     */
    public List<String> getAllCategories() {
        return productRepository.findAllCategories();
    }
    
    /**
     * 获取分类统计信息
     */
    public List<Object[]> getCategoryStatistics() {
        return productRepository.countByCategory();
    }
    
    /**
     * 将Product实体转换为ProductResponse
     */
    private ProductResponse convertToResponse(Product product) {
        return new ProductResponse(
                product.getId(),
                product.getName(),
                product.getDescription(),
                product.getPrice(),
                product.getStock(),
                product.getCategory(),
                product.getImageUrl(),
                product.getIsActive(),
                product.getCreatedAt(),
                product.getUpdatedAt()
        );
    }
} 